package com.glinsoft.ticktak.util;



import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.commons.codec.binary.Base64;


public class ImageBase64 {

    /**
     * 获取图片的BASE64编码
     * @param path
     * @return
     */
    public static String getBase64Src(String path) {
        InputStream in = null;
        byte[] data = null;
        try {
            in = new FileInputStream(path);
            data = new byte[in.available()];
            in.read(data);
            in.close();
            String src = new String(Base64.encodeBase64(data),"UTF-8");
            return src;
        }catch(Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 将BASE64编码的字符串写出到文件
     * @param src
     * @param path
     */
    public static void releaseToImage(String src,String path) {
        if (src == null || src.equals("")) {
            return;
        }
        try{
            byte[] b = Base64.decodeBase64(src.getBytes("UTF-8"));
            for(int i=0;i<b.length;++i){
                if(b[i]<0){
                    b[i]+=256;
                }
            }
            OutputStream out = new FileOutputStream(path);
            out.write(b);
            out.flush();
            out.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

}
